package com.itcast.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 定时客户端
 *
 * @author zheng.zhang
 */
@Slf4j
public class TimeClient {

    public static void main(String[] args) {
        new TimeClient().connect(8080, "localhost");
    }

    public void connect(int port, String host) {
        // 配置客户端
        log.info("客户端:[{}---->{}]", port, host);
        NioEventLoopGroup eventLoop = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoop).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) {
                            ByteBuf byteBuf = Unpooled.copiedBuffer("$".getBytes());
                            socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, byteBuf));
                            socketChannel.pipeline().addLast(new TimeClientHandler());
                        }
                    });
            // 绑定端口,同步等待成功
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            // 等待服务端监听端口关闭
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("客户端启动失败:{}", e.getMessage());
        } finally {
            // 关闭客户端
            eventLoop.shutdownGracefully();
        }
    }
}
